package com.citcc.api.controller;

import com.citcc.api.filter.JwtUtil;
import com.citcc.business.bean.CdzAppUser;
import com.citcc.business.bean.vo.AuthTokenVO;
import com.citcc.business.service.CdzAppUserService;
import com.citcc.common.base.AjaxResult;
import com.citcc.common.msg.Response;
import com.citcc.common.utils.ResponseUtil;
import com.citcc.common.utils.StringUtils;
import com.citcc.framework.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Api(tags = "认证服务")
@RestController
public class AuthController extends BaseController {

    @Autowired
    private JwtUtil jwtUtil;

    private final CdzAppUserService cdzAppUserService;

    public AuthController(CdzAppUserService cdzAppUserService) {
        this.cdzAppUserService = cdzAppUserService;
    }

    @ApiOperation("获取token")
    @SuppressWarnings("serial")
    @PostMapping("/auth")
    public AjaxResult login(CdzAppUser cdzAppUser) {
        String msg = cdzAppUserService.userLogin(cdzAppUser);
        if (StringUtils.isEmpty(msg)) {
            String jwt = jwtUtil.generateToken(cdzAppUser.getPhone());
            HashMap<String, String> token = new HashMap<String, String>() {{
                put("token", jwt);
            }};
            return success(200, token);
        } else {
            return error(msg);
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token值", required = true)
    })
    @PostMapping("/refreshToken")
    @ApiOperation(value = "刷新token", notes = "客户端初始化APP时调用该接口，并替换本地缓存的token值")
    public Response<AuthTokenVO> refreshToken(@RequestParam("token") String token) {
        try {
            AuthTokenVO authTokenVO = new AuthTokenVO();
            String phone = jwtUtil.validateToken(token);
            authTokenVO.setToken(jwtUtil.generateToken(phone));
            return ResponseUtil.success(authTokenVO);
        } catch (Exception e) {
            return ResponseUtil.authFail(null);
        }
    }
}